# Seymore - Content Management on Rails
# 
# Copyright (c) 2006 - 2007 Thomas Mango
# 
# For license information, please visit:
# http://code.google.com/p/seymore/
# 
# File created by Thomas Mango [tsmango@gmail.com]

class User < ActiveRecord::Base
  belongs_to :user_type
  has_many :revisions
  
  attr_accessor :password
  attr_accessible :user_type_id, :username, :password, :name, :email
  
  validates_uniqueness_of :username, :on => :create, :message => "must be unique"
  validates_presence_of :user_type_id, :username, :name, :email
  validates_presence_of :password, :on => :create
  
  def before_create
    self.hashed_password = User.hash_password(self.password)
  end
  
  def before_save
    if self.password != nil && self.password != ''
      self.hashed_password = User.hash_password(self.password)
    end
  end
  
  def can?(action)
    return user_type.actions.include?(Action.find_by_name(action))
  end
  
  def self.login(username, password)
    hashed_password = hash_password(password || "")
    find(:first, :conditions => ["username = ? and hashed_password = ?", username, hashed_password])
  end
  
  def try_to_login
    User.login(self.username, self.password)
  end
  
  private
  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end
end
